package com.mdd.front.controller;

import com.mdd.common.core.AjaxResult;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.user.User;
import com.mdd.front.LikeFrontThreadLocal;
import com.mdd.front.service.IDistributionService;
import com.mdd.front.service.ILoginService;
import com.mdd.front.service.ShareService;
import com.mdd.front.validate.ShareValidate;
import com.mdd.front.validate.common.PageValidate;
import com.mdd.front.vo.share.SharingInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/api/share")
@Api(tags = "分享管理")
public class ShareController {
    @Resource
    ShareService shareService;

    @Resource
    ILoginService iLoginService;

    @Resource
    IDistributionService iDistributionService;


    @GetMapping("/list")
    @ApiOperation("分享记录")
    public AjaxResult<Object> Sharing(@Validated PageValidate pageValidate,
                                      @RequestParam(defaultValue = "2") Integer isBuy,
                                      @RequestParam String queryTime){

        Integer userId = LikeFrontThreadLocal.getUserId();
        PageResult<SharingInfoVo> list = shareService.Sharing(pageValidate, userId, isBuy,queryTime);

        return AjaxResult.success(list);
    }
    @PostMapping("/share")
    @ApiOperation("分享埋点-绑定用户")
    public AjaxResult<Object> share(@Validated @RequestBody ShareValidate shareValidate) {
        Integer userId = LikeFrontThreadLocal.getUserId();
        Integer terminal = LikeFrontThreadLocal.getTerminal();
        Integer goodsId = shareValidate.getGoodsId();
        String username = shareValidate.getUsername();
        String password = shareValidate.getPassword();
        String inviteCode = shareValidate.getInviteCode();
        //判断账号是否注册
        User register = shareService.isRegister(username);
        if(register==null){//未注册，先注册账号
            iLoginService.register(username, password, terminal, inviteCode);
        }else {//已注册，判断用户是否填写邀请码(true为可以绑定)
            if(!iDistributionService.checkAbleBindLeader(register.getId(), inviteCode)){
                return AjaxResult.failed("绑定失败！");
            }
        }

        return shareService.share(userId,inviteCode,username,goodsId);
    }
}
